/**
 * created by 江心才子, 2019/8/9
 * Copyright (c) 2019, 270628297@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.wyl.base.binding

import android.content.Context
import android.graphics.Point
import android.graphics.drawable.Drawable
import android.os.Build
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.ImageView
import androidx.annotation.FloatRange
import androidx.databinding.BindingAdapter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.wyl.libbase.extend.dp2px
import com.wyl.libbase.extend.leftMargin
import com.wyl.libbase.extend.rightMargin
import com.wyl.base.BuildConfig
import com.wyl.base.R

/**
 * 项目名称：o2o
 * 创建人：江心才子
 * 创建时间：2019-08-09 11:56
 * 内容描述：
 * 修改说明：
 */
@BindingAdapter(
    value = ["url", "avatar", "roundCorner", "cornerRadius", "placeHolder", "error"],
    requireAll = false
)
fun loadImage(
    imageView: ImageView,
    url: String? = null,
    avatar: Boolean = false,
    roundCorner: Boolean = false,
    cornerRadius: Int = 0,
    holderDrawable: Drawable? = null,
    errorDrawable: Drawable? = null
) {
    if (url.isNullOrEmpty()) return
    when {
        avatar -> imageView.loadCircleImage(url)
        roundCorner -> imageView.loadRoundCornerImage(url)
        else -> imageView.loadImage(url)
    }
}

fun String.url() = if (contains("http")) this else BuildConfig.BASE_URL + this

private fun load(
    imageView: ImageView,
    url: String? = null,
    options: RequestOptions
) {
    Glide.with(imageView.context)
        .load(url?.url())
        .apply(options)
        .into(imageView)
}

/**
 * 加载图片
 */
fun ImageView.loadImage(path: String, placeholder: Int = R.drawable.placeholder, useCache: Boolean = false) {
    val options = getOptions(placeholder, useCache)
    load(this, path, options)
}

/**
 * 加载圆形图片
 */
fun ImageView.loadCircleImage(path: String, placeholder: Int = R.drawable.placeholder_circle, useCache: Boolean = false) {
    val options = getOptions(placeholder, useCache)
        .circleCrop()
        .placeholder(placeholder)
        .error(placeholder)
    load(this, path, options)
}

/**
 * 加载圆角图片
 */
fun ImageView.loadRoundCornerImage(
    path: String,
    roundingRadius: Int = context.dp2px(5f),
    placeholder: Int = R.drawable.placeholder,
    useCache: Boolean = false
) {
    val options = getOptions(placeholder, useCache).transforms(CenterCrop(),RoundedCorners(roundingRadius))
    Glide.with(context).load(path.url())
        .apply(options)
        .into(this)
}

/**
 * 取消加载
 */
fun ImageView.loadClear(context: Context) {
    Glide.with(context).clear(this)
}

/**
 * 按照图片的宽高比加载
 * 使用本属性的ImageView在xml布局中的width及height属性必须为WRAP_CONTENT
 * widthProportion 为相对于屏幕宽度的比例取值范围为0.0-1.0，当widthProportion=1.0时，ImageView的宽度为屏幕宽度
 * heightProportion为相对于图片宽度的显示比例
 */
fun ImageView.loadImageByProportion(@FloatRange(from = 0.0, to = 1.0) widthProportion: Float, heightProportion: Float) {
    this.adjustViewBounds = true
    var screenWidth: Int
    var wm: WindowManager = this.context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    if (wm == null) {
        screenWidth = this.context.resources.displayMetrics.widthPixels - leftMargin - rightMargin
    } else {
        var point = Point()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            wm.defaultDisplay.getRealSize(point)
        } else {
            wm.defaultDisplay.getSize(point)
        }
        screenWidth = point.x - leftMargin - rightMargin
    }
    var para = this.layoutParams
    para.width = (screenWidth * widthProportion).toInt()
    para.height = ViewGroup.LayoutParams.WRAP_CONTENT
    layoutParams = para
    maxWidth = (screenWidth * widthProportion).toInt()
    maxHeight = (screenWidth * widthProportion * heightProportion).toInt()
    scaleType = ImageView.ScaleType.CENTER_CROP
}


private fun ImageView.getOptions(placeholder: Int , useCache: Boolean = false): RequestOptions {
    val options = RequestOptions()
        .placeholder(placeholder)
        .error(placeholder)
        .fallback(placeholder)
//        .priority(Priority.HIGH)
//    if (useCache)
//        options.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
    return options
}

